package com.htthorizon.powersupply.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htthorizon.powersupply.domain.RdsGridTgVoltDf;
import com.htthorizon.powersupply.domain.TgVoltMonitor;
import com.htthorizon.powersupply.mapper.RdsGridTgVoltDfMapper;
import com.htthorizon.powersupply.service.RdsGridTgVoltDfService;
import com.htthorizon.powersupply.service.TgVoltMonitorService;
import com.htthorizon.powersupply.utils.OrgUtil;
import com.htthorizon.powersupply.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Brilliant
 * @description 针对表【rds_grid_tg_volt_df(实时电压)】的数据库操作Service实现
 * @createDate 2025-01-17 11:10:17
 */
@Service
@Slf4j
public class RdsGridTgVoltDfServiceImpl extends ServiceImpl<RdsGridTgVoltDfMapper, RdsGridTgVoltDf>
        implements RdsGridTgVoltDfService{

    @Autowired
    private TgVoltMonitorService tgVoltMonitorService;

    @Autowired
    private RdsGridTgVoltDfMapper rdsGridTgVoltDfMapper;

    @Override
    public List<Map<String, Object>> getNewCol() {
        return rdsGridTgVoltDfMapper.selectLatestNonNullColumns();
    }

    @Override
    public void compute() {
        log.info("开始计算低电压");
        compute(1, new ArrayList<>());
    }

    public void compute(int page, List<RdsGridTgVoltDf> list) {
        int pageSie = 1000;
        String dataDt = DatePattern.PURE_DATE_FORMAT.format(new Date());
        QueryWrapper<RdsGridTgVoltDf> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("data_dt",dataDt);
        queryWrapper.orderByAsc("meter_id");
        Page<RdsGridTgVoltDf> rdsGridTgVoltDfPage = new Page<>(page, pageSie);
        Page<RdsGridTgVoltDf> result = this.page(rdsGridTgVoltDfPage,queryWrapper);
        List<RdsGridTgVoltDf> records = result.getRecords();
        list.addAll(records);
        Map<String, List<RdsGridTgVoltDf>> meterMap = list.stream().collect(Collectors.groupingBy(RdsGridTgVoltDf::getMeterId));
        meterMap.forEach((k, v) -> {
            if (v.size() > 1) {
                // k= merterId

                //删除原来的meterId
                LambdaQueryWrapper<TgVoltMonitor> tgLoadMonitorQueryWrapper = new LambdaQueryWrapper<>();
                tgLoadMonitorQueryWrapper.eq(TgVoltMonitor::getMeterId, k);
                tgLoadMonitorQueryWrapper.eq(TgVoltMonitor::getDataDt, dataDt);
                tgVoltMonitorService.remove(tgLoadMonitorQueryWrapper);


                List<TgVoltMonitor> tgVoltMonitors = new ArrayList<>(97);
                for (int i = 1; i <= 96; i++) {
//                    boolean flag = false;
                    for (RdsGridTgVoltDf gridTgVoltDf : v) {
                        if (StringUtils.isEmpty(gridTgVoltDf.getLineNm())) {
                            continue;
                        }
                        JSONObject jsonObjectGridTgVoltDf = new JSONObject(gridTgVoltDf);
                        Object o = jsonObjectGridTgVoltDf.get("val" + i);
                        if (o != null) {
                            double val_i = Double.parseDouble((String) o);
                            if ((val_i >= 110 && val_i <= 198)) {
                                TgVoltMonitor tgVoltMonitor = new TgVoltMonitor();
                                BeanUtils.copyProperties(gridTgVoltDf, tgVoltMonitor, "id");
                                tgVoltMonitor.setTime(i);
                                tgVoltMonitor.setTgVolt(String.valueOf(val_i));
                                tgVoltMonitor.setStdCountyOrgNm(OrgUtil.map(tgVoltMonitor.getStdCountyOrgNm()));
                                String timeFormat = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
                                tgVoltMonitor.setApperTime(timeFormat + " " + TimeUtil.getTimeByIndex(i));
                                tgVoltMonitors.add(tgVoltMonitor);
//                                flag = true;
                                break;
                            }
                        }
                    }
//                    if (flag) {
//                        break;
//                    }
                }
                tgVoltMonitorService.saveBatch(tgVoltMonitors);
                records.removeAll(v);
            }
        });
        if (result.hasNext()) {
            page++;
            compute(page, records);
        }
    }

    @Override
    public Map<String, Object> getChart(String meterId) {
        String dataDt = DatePattern.PURE_DATE_FORMAT.format(new Date());
        LambdaQueryWrapper<RdsGridTgVoltDf> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RdsGridTgVoltDf::getMeterId, meterId);
        wrapper.eq(RdsGridTgVoltDf::getDataDt, dataDt);
        wrapper.in(RdsGridTgVoltDf::getPhaseFlg, "1", "2", "3");

        HashMap<String, Object> map = new HashMap<>();
        map.put("a", new String[96]);
        map.put("b", new String[96]);
        map.put("c", new String[96]);
        map.put("date", dataDt);

        List<RdsGridTgVoltDf> list = this.list(wrapper);
        for (RdsGridTgVoltDf rdsGridTgVoltDf : list) {
            if ("1".equals(rdsGridTgVoltDf.getPhaseFlg())) {
                String[] a = rdsGridTgVoltDf.mapArray();
                map.put("a", a);
            } else if ("2".equals(rdsGridTgVoltDf.getPhaseFlg())) {
                String[] b = rdsGridTgVoltDf.mapArray();
                map.put("b", b);
            } else if ("3".equals(rdsGridTgVoltDf.getPhaseFlg())) {
                String[] c = rdsGridTgVoltDf.mapArray();
                map.put("c", c);
            }
        }
        return map;
    }
}




